<?php

namespace app\purchase\model;

use app\purchase\model\Goods as GoodsModel;
use app\purchase\model\GoodsSpec as GoodsSpecModel;
use app\purchase\model\GoodsSpecValue as GoodsSpecValueModel;
use think\Db;

class Order extends \PurchaseModel
{
    protected $table = 'sh_order';

    protected $pk = 'order_id';

    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    protected $createTime = 'create_at';

    protected $insert = ['order_sn'];

    public function orderDb(){
        return Db::name('order');
    }

    public function customer(){
        return $this->belongsTo('Customer','customer_id')->field('customer_name');
    }

    public function orderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_id');
    }

    public function orderLog(){
        return $this->hasMany('OrderLog','order_id');
    }

    public function orderAddress(){
        return $this->hasMany('OrderAddress','order_id');
    }

    protected function setOrderSnAttr()
    {
        return $this->generateOrderSn();
    }

    public function generateOrderSn()
    {
        $dateString = sprintf('%09d', time() - 1544745600);

        mt_srand((double) microtime() * 10000);
        $randString = sprintf('%05d', mt_rand(1, 99999));

        $orderNoTmp = substr($dateString, 4, 3)
            . substr($randString, 0, 2)
            . substr($dateString, 0, 2)
            . substr($dateString, 7)
            . substr($dateString, 2, 2)
            . substr($randString, 2);

        $count = $this->where([
            'order_sn' => $orderNoTmp,
        ])->count('order_sn');
        if ($count) return $this->generateOrderSn();

        return $orderNoTmp;
    }

    /**
     * 简单搜索
     * @return array
     */
    public function easySearch($params){

        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 20;

        $where = [];

        if(!empty($params['status'])){
            $where['order.status'] = ['in',$params['status']];
        }

        if(!empty($params['date'])){
            $filter_date = array_map(function($date){
                return strtotime($date);
            },$params['date']);
            $where['order.create_at'] = ['between',$filter_date];
        }
        
        if(!empty($params['query'])){
            $where['order.order_sn | customer.customer_name'] = ['like','%'.$params['query'].'%'];
        }

        $data = $this->alias('order')
        ->join('sh_customer customer','customer.customer_id = order.customer_id')
        ->field('customer.customer_name,order.*')
        ->where($where)
        ->page($page,$pageSize)->select();

        return $data;
    }

    /**
     * 高级搜索
     * @return array
     */
    public function search($params){

        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 10;

        $where = [];
        $where['order.client_id'] = \request()->header('company');
        //订单号
        if(!(empty($params['order_sn']))){
            $where['order.order_sn'] = ['like','%'.$params['order_sn'].'%'];
        }
        //下单时间
        if(!empty($params['date'])){
            $filter_date = array_map(function($date){
                return strtotime($date);
            },$params['date']);
            $where['order.order_time'] = ['between',$filter_date];
        }


        //收货地址
        if(!empty($params['address'])){
            $where['address.client_name | address.mobile |address.consignee'] = ['like','%'.$params['address'].'%'];
        }
        //商品信息
        if(!empty($params['goods'])){
            $where['order.search_goods'] = ['like','%'.$params['goods'].'%'];
        }
        //
        //制单人
        if(!empty($params['make'])){
            $where['order.make'] = ['like','%'.$params['make'].'%'];
        }
        //业务员
        if(!empty($params['salesman_id'])){
            $where['order.salesman_id'] = $params['salesman_id'];
        }
        //所属部门
        if(!empty($params['department_id'])){
            $where['order.department_id'] = $params['department_id'];
        }
        //发货仓库
        if(!empty($params['warehouse_id'])){
            $where['order.warehouse_id'] = $params['warehouse_id'];
        }
        //打印状态
        if(!empty($params['print_status'])){
            $where['order.gathering_type'] = $params['print_status'];
        }
        //订单状态
        if(!empty($params['status'])){
            $where['order.type'] = $params['status'];
        }
        //收款状态
        if(!empty($params['pay_status'])){
            $params['pay_status'] = array_keys($params['pay_status']);
            $where['order.gathering_type'] = ['in',$params['pay_status']];
        }

        $data = $this->orderDb()->alias('order')
        ->join('sh_client client','client.client_id = order.client_id','left')
        ->join('sh_order_address address','address.order_id = order.order_id','left')
        ->field('order.order_id,order.order_sn,order.gathering_type,order.order_time,order.make,client.client_name,order.price,order.price,order.out_warehouse,order.deliver_goods,order.type,address.area,address.consignee,address.address,address.mobile')
        ->group('order.order_id')
        ->where($where)
        ->page($page,$pageSize)->select();

        foreach($data as &$v){
            $log = Db::name('order_operate_log')->where('order_id',$v['order_id'])->field('create_at,desc')->order('create_at desc')->limit(1)->find();
            $v['create_at'] = $log['create_at'];
            $v['desc'] = $log['desc'];
            $v['area'] = !empty($v['area']) ? explode(',',$v['area']) : [];
        }

        $total = $this->alias('order')
            ->join('sh_client client','client.client_id = order.client_id','left')
            ->join('sh_order_address address','address.order_id = order.order_id','left')
            ->group('order.order_id')
            ->where($where)
            ->count();

        $pager = [
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $total
        ];
        return [
            'data' => $data,
            'pager' => $pager
        ];

    }

    //获取状态翻译
    public function getDeliverGoodsStatusTrans($status){
        $all_status = array(
            0 => '待发货',
            1 => '部分发货',
            2 => '已发货',

        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }
    //获取状态翻译
    public function getWarehouseStatusTrans($status){
        $all_status = array(
            0 => '备货中',
            1 => '部分出库',
            2 => '已出库',

        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }
    //获取状态翻译
    public function getStatusTrans($status){
        $all_status = array(
            0 => '待订单审核',
            1 => '待财务审核',
            2 => '待出库审核',
            3 => '待发货确认',
            4 => '待收货确认',
            5 => '已完成',
            6 => '已作废'
        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知'; 
    }

    //财务翻译
    public function getFinanceStatusTrans($status){
        $all_status = array(
            0 => '收款待审核',
            1 => '未收款',
            2 => '已收款',

        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }

    //获取订单详情
    public function getOrderDetail($id){

        $orderDb = $this->orderDb();
        $order = $orderDb->alias('a')->join('sh_client c','a.client_id=c.client_id')->where('order_id',$id)->field('a.*,c.client_name')->find();
        $order['type_trans'] = $this->getStatusTrans($order['type']);//订单状态翻译
        $order['delivery_time'] = date('Y-m-d H:i:s',$order['delivery_time']);
        $order['order_time'] = date('Y-m-d H:i:s',$order['order_time']);
        $order['gathering_type']  = $this->getFinanceStatusTrans($order['gathering_type']);//财务翻译
        $OrderGoods = new OrderGoods();
        $OrderGoodsDb = $OrderGoods->OrderGoodsDb();
        $goods = $OrderGoodsDb->alias('a')->join('sh_goods_unit g','a.unit_id = g.unit_id','left')->where('a.order_id',$id)->field('a.*,g.unit_name')->select();
        $OrderAccessoryModel = new OrderAccessory();
        $OrderAccessoryDb = $OrderAccessoryModel->OrderAccessoryDb();
        $Accessory = $OrderAccessoryDb->alias('a')->join('sh_accessory c','a.accessory_id = c.accessory_id')->where('a.order_id',$id)->field('accessory_url url,accessory_name name')->select();
        
        foreach($Accessory as &$acc){
            $acc['url'] = $acc['url'].'|'.$acc['name']; 
        }

        $OrderAddress = new OrderAddress();
        $OrderAddressDb = $OrderAddress->OrderAddressDb();
        $address = $OrderAddressDb->where('order_id',$id)->order('save_time desc')->find();
        $address['area'] = !empty($address['area']) ? explode(',',$address['area']) : [];
        $OrderBill = new OrderBill();
        $OrderBillDb = $OrderBill->OrderBillDb();
        $Bill = $OrderBillDb->where('order_id',$id)->find();
        //获取订单操作日志
        $OrderLog = new OrderLog();
        $OrderLogDb = $OrderLog->OrderLogDb();
        $log = $OrderLogDb->where('order_id',$id)->order('create_at desc')->select();
        foreach ($log as $k=>$v){
            $log[$k]['create_at'] = date('Y-m-d H:i:s',$log[$k]['create_at']);
        }
        return [
            'order' => $order,//订单详情
            'goods' => $goods,//商品数据
            'address' => $address,//订单地址
            'bill' => $Bill,//发票数据
            'accessory' => $Accessory,//附件
            'log'=>$log//获取订单操作日志
        ];
    }

}
